from sqlalchemy import or_, and_

from easyRead.api import bp
from easyRead.extensions import db
from easyRead.api.errors import bad_request, error_response
from flask import request, jsonify, url_for, g, current_app, make_response
from easyRead.models import QRcode, BorrowingLibraryBook, User, State, BorrowingHistory
import qrcode
import datetime


@bp.route('/qrcode/<userid>/<bookid>', methods=['POST'])  # 新增一个二维码，一个用户不能借同一本书两次
def add_qrcode(userid, bookid):
    # 先判断用户是否已有二维码，默认用户一次只能持有一个二维码
    qrcode = QRcode.query.filter(QRcode.borrower_id == userid).first()
    if qrcode is not None:
        return make_response("You can only process one QR code", "403")
    # 判断用户是否借过多的书
    user_borrow_number = BorrowingLibraryBook.query.filter(BorrowingLibraryBook.borrower_id == userid).count()
    user_level = User.query.filter(User.id == userid).first().level
    if user_level == "student" and user_borrow_number > 6:
        return make_response("You can only borrow six books", "403")
    if user_level == "teacher" and user_borrow_number > 10:
        return make_response("You can only borrow ten books", "403")
    # 条件满足，生成二维码，供用户借书
    time  = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    QRcode_text = "userid:" + userid + " bookid:" + bookid + " time:" + time
    qrcode = QRcode(bookid, userid, QRcode_text, State.NOT_TAKEN, time)
    db.session.add(qrcode)
    try:
        db.session.commit()
    except Exception as e:
        # 回滚会话，取消之前的修改
        db.session.rollback()


    return make_response(QRcode_text,"200")


@bp.route('/qrcode/<qrcode_text>', methods=['GET'])  # 查询一个二维码
def get_qrcode(qrcode_text):
    qrcode = QRcode.query.filter(QRcode.QR_code == qrcode_text).first()
    # 按空格分割字符串并遍历分割后的列表
    for item in qrcode_text.split(' '):
        if 'userid:' in item:  # 如果字符串中包含 'userid:'，则取出相应的值
            userid = item.split(':')[1]
        elif 'bookid:' in item:  # 如果字符串中包含 'bookid:'，则取出相应的值
            bookid = item.split(':')[1]

    if qrcode is None:
        return make_response("Invalid QR code", "404")
    # 如果还未取走，此时用户取走书籍
    if qrcode.state == State.NOT_TAKEN:
        qrcode.state = State.TAKEN
        time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        borrowing_library_book = BorrowingLibraryBook(bookid, userid, time)
        db.session.add(borrowing_library_book)
        try:
            db.session.commit()
        except Exception as e:
            # 回滚会话，取消之前的修改
            db.session.rollback()

        return jsonify()
    # 如果已经取走，此时用户归还书籍(删除QRcode，删除图书借阅信息，加一个借阅历史)
    if qrcode.state == State.TAKEN:
        borrowing_library_book_before = BorrowingLibraryBook.query.filter(and_(BorrowingLibraryBook.borrower_id == userid , BorrowingLibraryBook.book_id == bookid)).first()
        borrowing_history = BorrowingHistory(bookid, userid, borrowing_library_book_before.time, datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        db.session.add(borrowing_history)
        db.session.delete(borrowing_library_book_before)
        db.session.delete(qrcode)
        try:
            db.session.commit()
        except Exception as e:
            # 回滚会话，取消之前的修改
            db.session.rollback()

        return jsonify()